package com.niit.user_profile_center.service;

import com.niit.user_profile_center.entity.Activity;
import com.niit.user_profile_center.entity.User;
import com.niit.user_profile_center.mapper.UserMapper;
import com.niit.user_profile_center.utils.QiniuUtil;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.stereotype.Service;



import javax.transaction.Transactional;
import java.util.List;

@Service
public class UserService {
    private UserMapper userMapper;
    private QiniuUtil qiniuUtil; // 添加 QiniuUtil 字段
    public UserService(UserMapper userMapper, QiniuUtil qiniuUtil){ // 修改构造函数
        this.userMapper = userMapper;
        this.qiniuUtil = qiniuUtil;
    }
    public User getUserById(Long id){
         return userMapper.selectById(id);
    }
    //修改个人资料
    @Transactional
    public boolean  updateProfile(User user){

        // 添加日志输出
        System.out.println("开始更新用户资料: ID=" + user.getId());
        System.out.println("用户名: " + user.getUsername());
        System.out.println("昵称: " + user.getNickname());
        System.out.println("邮箱: " + user.getEmail());
        System.out.println("电话: " + user.getPhone());
        System.out.println("简介: " + user.getBio());

        // 校验用户是否存在（可通过JPA查询补充）
        // User existUser = userRepository.findById(user.getId()).orElse(null);
        // if (existUser == null) throw new Exception("用户不存在");

        int result = userMapper.updateUserProfile(user);

        if (result > 0) {
            System.out.println("用户资料更新成功: ID=" + user.getId());
            return true;
        } else {
            System.out.println("用户资料更新失败: ID=" + user.getId());
            return false;
        }
    }
    /**
     * 获取用户动态信息
     *
     * @param userId 用户ID，用于查询用户动态
     * @return 返回一个包含用户动态信息的列表
     */
    public List<Activity> getUserActivity(Long userId) {
        return userMapper.getUserActivity(userId);
    }
    // 获取用户粉丝数
    public int getFollowerCount(Long userId) {
        return userMapper.getFollowerCount(userId);
    }

    // UserService.java
    public User findUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }


    public List<User> getFollowingUsers(Long id) {
        return userMapper.getFollowingUsers(id);


    }
    //七牛云上传头像
    @Transactional
    public String updateAvatar(Long userId, MultipartFile file) throws Exception {
        // 检查用户是否存在
        User user = getUserById(userId);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        // 上传文件并获取访问URL
        String avatarUrl = qiniuUtil.uploadFile(file.getInputStream(), file.getOriginalFilename());

        // 更新用户头像URL
        user.setAvatar(avatarUrl);
        userMapper.updateUserProfile(user);

        return avatarUrl;
    }
}
